package com.lazyframework.security.web.extra.weixin;

import com.lazyframework.security.web.authentication.UserDetails;
import com.lazyframework.security.web.authentication.provider.AbstractAuthenticationProvider;
import com.lazyframework.security.web.authentication.token.Authentication;
import com.lazyframework.security.web.exception.AuthenticationException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

import static com.lazyframework.security.web.extra.weixin.OpenIDResponseStatus.INVALID_CODE;

/**
 * 微信OpenID认证Provider
 *
 * @author maoning
 */
@Slf4j
public class OpenIDAuthenticationProvider extends AbstractAuthenticationProvider {

    private String appid;

    private String secret;

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    @Override
    protected Authentication doAuthenticate(Authentication authentication) throws AuthenticationException {
        OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) authentication;

        // 获取OpenID
        WxAuthResult authResult;
        try {
            authResult = new WxAuthService(appid, secret).auth((String) token.principal(), token.authType());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new OpenIDAuthenticationException(String.valueOf(INVALID_CODE.value()), e.getMessage());
        }

        // 根据openid查询用户信息
        UserDetails userDetails = userDetailsService().loadByOpenID(authResult.getOpenid());

        // 认证成功
        OpenIDAuthenticationToken auth = new OpenIDAuthenticationToken(userDetails);
        auth.setAuthenticated(true);

        return auth;
    }

    @Override
    public boolean support(Class<?> auth) {
        return OpenIDAuthenticationToken.class.isAssignableFrom(auth);
    }

}
